#include "stdafx.h"
#include "CommonContents.h"

using namespace MomogenkyouContent;

bool	KeywordTextures::Initialize(const std::string & XMLDefinition, MomogenkyouSystem::ContentManager * pContentManager)
{
	//	OpenXML
	//	Load etc
	XML	_System_TextFile(XMLDefinition.c_str());

	XMLElement	*	_Root	=	_System_TextFile.GetRootElement();
	XMLElement	*	_Sets	=	_Root->FindElementZ("Sets");
	XMLElement	**	_List	=	_Sets->GetChildren();
	XMLElement	*	_Parser	=	NULL;
	MomogenkyouSystem::TextureData	*	_Texture(NULL);
	MomogenkyouSystem::TextureFrame		_Frame;

	std::string	_Path, _Id;
	char		_Buffer[256];

	for(size_t i = 0; i < _Sets->GetChildrenNum(); i++)
	{
		_Parser = _List[i];
		_Path.clear();
		memset(_Buffer, 0x00, 256);
		_Parser->FindVariableZ("Path")->GetValue(_Buffer);
		_Path = _Buffer;

		_Id.clear();
		memset(_Buffer, 0x00, 256);
		_Parser->FindVariableZ("Path")->GetValue(_Buffer);
		_Id = _Buffer;

		_Texture = pContentManager->LoadTexture(_Path);

		m_KeywordAtlas.insert(std::make_pair(_Id, _Texture));
	}

	_Sets	=	_Root->FindElementZ("Texts");
	_List	=	_Sets->GetChildren();
	for(size_t i = 0; i < _Sets->GetChildrenNum(); i++)
	{
		_Parser = _List[i];

		_Path.clear();
		memset(_Buffer, 0x00, 256);
		_Parser->FindVariableZ("Id")->GetValue(_Buffer);
		_Path = _Buffer;

		_Frame.m_Coord.x = _Parser->FindVariableZ("x")->GetValueFloat() / _Texture->Width;
		_Frame.m_Coord.y = _Parser->FindVariableZ("y")->GetValueFloat() / _Texture->Height;

		_Frame.m_Size.x = _Parser->FindVariableZ("w")->GetValueFloat() / _Texture->Width;
		_Frame.m_Size.y = _Parser->FindVariableZ("h")->GetValueFloat() / _Texture->Height;

		m_KeywordFrames.insert(std::make_pair(_Path.c_str(), _Frame));
	}
	return true;
}

bool	KeywordTextures::Shutdown()
{
	m_KeywordAtlas.clear();
	m_KeywordFrames.clear();
	return true;
}

MomogenkyouSystem::TextureData	*	KeywordTextures::FindKeywordAtlus(const std::string & Name)
{
	std::map<std::string, MomogenkyouSystem::TextureData *>::iterator it = m_KeywordAtlas.find(Name.c_str());
	if(it != m_KeywordAtlas.end())
		return it->second;
	WriteCommandLine("CommonContents > Atlus not found - %s", Name.c_str());
	return NULL;
}

MomogenkyouSystem::TextureFrame		KeywordTextures::FindKeywordFrame(const std::string & Name)
{
	std::map<std::string, MomogenkyouSystem::TextureFrame>::iterator it = m_KeywordFrames.find(Name.c_str());
	if(it != m_KeywordFrames.end())
		return it->second;
	WriteCommandLine("CommonContents > Keyword not found - %s", Name.c_str());
	return MomogenkyouSystem::TextureFrame();
}